package com.tungse.study.itreator_mode;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

public class UserFile implements Iterable<UserOne>{
    private final File file;

    public UserFile(File file) {
        this.file = file;
    }

    @Override
    public Iterator<UserOne> iterator() {
        return new UserFileIterator();
    }

    class UserFileIterator implements Iterator<UserOne> {
        int cursor = 0;
        List<UserOne> userOneList = loadUserFromFile();

        private List<UserOne> loadUserFromFile() {
            try {
                List<String> strings = Files.readAllLines(file.toPath());
                return strings.stream().map(line -> {
                    String substring = line.substring(1, line.length() - 1);
                    String[] split = substring.split(",");
                    return new UserOne(split[0], Integer.parseInt(split[1]));
                }).collect(Collectors.toList());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        public boolean hasNext() {
            return cursor != userOneList.size();
        }

        @Override
        public UserOne next() {
            if(cursor>=userOneList.size()) {
                throw new NoSuchElementException();
            }
            int currentIndex = cursor;
            cursor++;
            return userOneList.get(currentIndex);
        }
    }
}
